package com.chy.blog_web.modular.web.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chy.blog_web.core.el.ELSession;
import com.chy.blog_web.core.util.SendSmsUtil;
import com.chy.blog_web.core.util.SpaceUserUtil;
import com.chy.blog_web.modular.sharCore.ScheduleTask;
import com.chy.blog_web.modular.web.entity.*;
import com.chy.blog_web.modular.web.mapper.BoLoveListMapper;
import com.chy.blog_web.modular.web.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述：恋爱清单表 service业务层
 * 作者：chenhuiyan
 * 时间：2020/04/10
 */
@Service
@Transactional(readOnly = true)
public class BoLoveListServiceImpl extends ServiceImpl<BoLoveListMapper, BoLoveList> implements IBoLoveListService {

    Logger logger = LoggerFactory.getLogger(ScheduleTask.class);

    @Autowired
    private IBoLoveListService loveListService;

    @Autowired
    private IBoDynamicService dynamicService;

    @Autowired
    private IBoSpaceUserService spaceUserService;

    @Autowired
    private IBoInfoSendMrgService infoSendMrgService;

    @Autowired
    private IBoMsgTemplateService msgTemplateService;

    @Autowired
    private IBoMsgSignService msgSignService;

    /**
     * 查询未写感受列表
     * @param params
     * @return
     */
    public List<Map<String, Object>> list(Map<String, Object> params){
        return baseMapper.list(params);
    }

    /**
     * 查询未写感受总数
     * @param params
     * @return
     */
    public int getCount(Map<String, Object> params){
        return baseMapper.getCount(params);
    }

    /**
     * 查询详情
     * @param id
     * @return
     */
    public Map<String, Object> getInfoById(String id){
        return baseMapper.getInfoById(id);
    }

    /**
     * 查询亲蜜度
     * @return
     */
    public int getSweet(){
        return baseMapper.getSweet();
    }

    /**
     * 发起恋爱清单
     * @param boLoveList
     */
    @Transactional
    public void sendLoveList(BoLoveList boLoveList, BoSpaceUser spaceUser){

        //保存清单
        boLoveList.preInsert();
        boLoveList.setSpaceUserId(spaceUser.getId());
        loveListService.save(boLoveList);

        //生成发起恋爱清单动态
        BoDynamic boDynamic = new BoDynamic();
        boDynamic.preInsert();
        boDynamic.setServiceId(boLoveList.getId());
        boDynamic.setContent(boLoveList.getContent());
        boDynamic.setType(2);
        boDynamic.setSpaceUserId(spaceUser.getId());
        dynamicService.save(boDynamic);

        //**************************发送短信********************

        //空间用户他
        BoSpaceUser spaceUserToHe = spaceUserService.getOne(new QueryWrapper<BoSpaceUser>()
                .eq("type", 0)
                .ne("status", 2)
                .eq("del_flag", 0));

        //空间用户她
        BoSpaceUser spaceUserToHer = spaceUserService.getOne(new QueryWrapper<BoSpaceUser>()
                .eq("type", 1)
                .ne("status", 2)
                .eq("del_flag", 0));

        //手机号、接收人
        String[] phoneNumbers = {spaceUserToHe.getPhone(), spaceUserToHer.getPhone()};
        String[] receiveName = {spaceUserToHe.getUserName(), spaceUserToHer.getUserName()};

        //******************变量长度处理（不超过20）********************

        String content = "";
        if(boLoveList.getContent().length() > 20){
            content = boLoveList.getContent().substring(0, 17) + "...";
        }else{
            content = boLoveList.getContent();
        }

        //获取签名
        BoMsgSign msgSign = msgSignService.getOne(new QueryWrapper<BoMsgSign>().eq("use_status", 0));
        String singName = SendSmsUtil.SIGNNAME_CODE;
        if(ObjectUtil.isNotEmpty(msgSign)){
            singName = msgSign.getSignName();
        }

        //获取模板信息
        String temCode = SendSmsUtil.TEMPLATE_CODE_LOVE_LIST;
        BoMsgTemplate msgTemplate = msgTemplateService.getOne(new QueryWrapper<BoMsgTemplate>().eq("code", temCode));

        if(ObjectUtil.isNotEmpty(msgTemplate)){
            //短信模板变量（变量属性:uaerName-其他；content-其他）
            JSONObject tJson = JSONUtil.createObj()
                    .put("uaerName", spaceUser.getUserName())
                    .put("content", content);
            String templateParam = JSONUtil.toJsonStr(tJson);
            logger.info(">>>>>>>>>发起恋爱清单-短信模板变量tJson：{}", tJson);
            for(int i = 0; i < phoneNumbers.length; i++){
                logger.info(">>>>>>>>>发起恋爱清单-接收手机号：{}", phoneNumbers[i]);
                String dataStr = SendSmsUtil.SendSms(phoneNumbers[i], singName, temCode, templateParam);
                logger.info(">>>>>>>>>发起恋爱清单-发送结果：{}", dataStr);

                //生成信息发送记录
                infoSendMrgService.saveMsgLog(dataStr, msgTemplate, tJson, receiveName[i], phoneNumbers[i], 5, "");
            }
        }else{
            logger.info(">>>>>>>>>发起恋爱清单-短信模板不存在,无法发送短信：{}", temCode);
        }
    }
}
